package com.jinzhi.jzweb.controller;


import java.net.URLEncoder;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.service.EvaluationService;
import com.jinzhi.common.utils.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2021-10-20 14:11:17 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/evaluation")
public class EvaluationController extends BaseController {
	@Autowired
	private EvaluationService evaluationService;
	
	@GetMapping()
	@RequiresPermissions("jzweb:evaluation:evaluation")
	String Evaluation(){
	    return "jzweb/evaluation/evaluation";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:evaluation:evaluation")
	public Result<Page<EvaluationDO>> list(HttpServletRequest req,EvaluationDO evaluationDTO){
		// 查询列表数据
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			String orgName = this.getUser().getOrgName();
			if(orgName==null){
				return Result.fail("账号所属机构有误，请联系平台管理员！");
			}
			Page<EvaluationDO> page = evaluationService.selectPage(getPage(EvaluationDO.class),
					evaluationService.convertToEntityWrapper("school",orgName)
							.orderBy("id", false));
			List list = new ArrayList();
			for (int i = 0; i < page.getRecords().size(); i++) {
				EvaluationDO obj = (EvaluationDO) page.getRecords().get(i);
				list.add(obj);
			}
			page.setRecords(list);
			return Result.ok(page);
		}else{
			Page<EvaluationDO> page = evaluationService.selectPage(getPage(EvaluationDO.class),
					evaluationService.convertToEntityWrapper("school",evaluationDTO.getSchool())
							.orderBy("id", false));
			List list = new ArrayList();
			for (int i = 0; i < page.getRecords().size(); i++) {
				EvaluationDO obj = (EvaluationDO) page.getRecords().get(i);
				list.add(obj);
			}
			page.setRecords(list);
			return Result.ok(page);
		}


	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:evaluation:add")
	String add(){
	    return "jzweb/evaluation/add";
	}

	@GetMapping("/edit/{name}")
	@RequiresPermissions("jzweb:evaluation:edit")
	String edit(@PathVariable("name") String name,Model model){
		EvaluationDO evaluation = evaluationService.selectById(name);
		model.addAttribute("evaluation", evaluation);
	    return "jzweb/evaluation/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:evaluation:add")
	public Result<String> save( EvaluationDO evaluation){
		evaluationService.insert(evaluation);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:evaluation:edit")
	public Result<String>  update( EvaluationDO evaluation){
		boolean update = evaluationService.updateById(evaluation);
		return update ? Result.ok() : Result.fail();
	}

	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:evaluation:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<EvaluationVO> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "实操成绩导入模板", "实操成绩导入模板", EvaluationVO.class, "实操成绩导入模板", response);
	}

	/**
	 * 成绩导出
	 * */
	@GetMapping("/exportList")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:evaluation:exportList")
	public void exportlist(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map map = new HashMap();
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			String orgName = this.getUser().getOrgName();
			if (orgName == null) {
				return ;
			}
			map.put("school",orgName);
		}else{
			map.put("school",null);
		}
		List<EvaluationExportVO> evaluationExportVO = evaluationService.exportList(map);
		if(evaluationExportVO.size()<=0)
			return;
		EasyPoiUtil.exportExcel(evaluationExportVO, "实操考试成绩", "实操考试成绩", EvaluationExportVO.class,"实操考试成绩", response);
	}

	/**
	 * 考生信息导入
	 *
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:evaluation:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<EvaluationVO> list = EasyPoiUtil.importExcel(file, 1, 1, EvaluationVO.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<EvaluationDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getName())) {
				sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getAdmissionNumber())) {
					sb.append("第" + (i + startRow) + "行准考证号未填写，请完善！" + ";");
				} else {
					if (StringUtils.isBlank(list.get(i).getSchool())) {
						sb.append("第" + (i + startRow) + "行学校未填写，请完善！" + ";");
					} else {
						if (StringUtils.isBlank(list.get(i).getPracticalOperation().toString())) {
							sb.append("第" + (i + startRow) + "行成绩未填写，请完善！" + ";");
						} else {

							if (sb.length() == 0) {
								//第四步排重验证（自身比较）
								for (int j = 0; j < list.size(); j++) {
									if (i != j) {
										if (list.get(i).getAdmissionNumber().equals(list.get(j).getAdmissionNumber())) {
											sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getAdmissionNumber() + ";");
										}
									}
								}


//								//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
								EvaluationDO stuSignUpDO = evaluationService.findOneByKv("admission_number", list.get(i).getAdmissionNumber(), "name", list.get(i).getName());
								if (stuSignUpDO != null) {
									sb.append("第" + (i + startRow) + "行考生成绩已导入！" + ";");
								}

							}
						}
					}
				}
			}


				EvaluationDO stuSignUpDO1 = new EvaluationDO();

				stuSignUpDO1.setName(list.get(i).getName());//姓名
				stuSignUpDO1.setAdmissionNumber(list.get(i).getAdmissionNumber());//准考证
				stuSignUpDO1.setSchool(list.get(i).getSchool());//学校
				stuSignUpDO1.setPracticalOperation(list.get(i).getPracticalOperation());//成绩


				upDOList.add(stuSignUpDO1);

				if (sb.length() > 0) {
					ErrorCodeVo errorCodeVo = new ErrorCodeVo();
					errorCodeVo.setSeq(cout);
					cout += 1;
					errorCodeVo.setErrorCode(sb.toString());
					list1.add(errorCodeVo);
				}

			}

			if (list1.size() == 0) {
				boolean c = evaluationService.insertBatch(upDOList, upDOList.size());
				if (c) {

					return Result.ok("成功导入" + list.size() + "条数据");
				} else {
					return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
				}
			} else {

				JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
				//将list1存到缓存中
				EhCacheUtil.put("evaluationService" + this.getUserId(), jsonArray);
				return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
			}

		}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:evaluation:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("成绩导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("evaluationService" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:evaluation:remove")
	public Result<String>  remove( Long id){
		evaluationService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:evaluation:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") String[] ids){
		evaluationService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
